//
//  YCLogManager.m
//  YCLog
//
//  Created by 唐可雄 on 16/8/29.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCLogManager.h"

#import "FMDB.h"

#define YCLog_DB                    @"log.db"
#define YCLog_Table_Log             @"log"
#define YCLog_Table_Log_ID          @"rowid"    /// sqlite自带的
#define YCLog_Table_Log_CreateTime  @"createtime"
#define YCLog_Table_Log_Content     @"content"

static YCLogManager *manager = nil;

@interface YCLogManager ()

/// 数据库对象
@property (strong, nonatomic) FMDatabase *db;

@end

@implementation YCLogManager

#pragma mark - Life Cycle

- (instancetype)init {
    self = [super init];
    
    if (self) {
        [self initDataBase];
    }
    
    return self;
}

- (void)initDataBase {
    [self.db open];
    
    [self ceateLogTable];
}

- (void)dealloc {
    [self.db close];
    self.db = nil;
}

#pragma mark - Setter and Getter

- (FMDatabase *)db {
    if (_db == nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = paths.firstObject;
        if (docDir) {
            NSString *path = [docDir stringByAppendingPathComponent:YCLog_DB];
            _db = [[FMDatabase alloc] initWithPath:path];
        }
    }
    
    return _db;
}

#pragma mark - Table Handle

/**
 *  创建表
 *
 *  @param tableName 表名
 *  @param sql       创建语句
 */
- (void)createTable:(NSString *)tableName sql:(NSString *)sql {
    BOOL isExist = [self.db tableExists:tableName];
    if (!isExist) {
        [self.db executeUpdate:sql];
    }
}

/**
 *  创建表
 */
- (void)ceateLogTable {
    [self createTable:YCLog_Table_Log sql:[NSString stringWithFormat:@"CREATE TABLE %@ (%@ LONG, %@ TEXT)", YCLog_Table_Log, YCLog_Table_Log_CreateTime, YCLog_Table_Log_Content]];
}

/**
 *  插入日志
 *
 *  @param log 日志
 *
 *  @return 是否插入成功
 */
- (BOOL)insertLog:(NSString *)log {
    return [self.db executeUpdate:[NSString stringWithFormat:@"INSERT INTO %@ (%@, %@) VALUES (?, ?)", YCLog_Table_Log, YCLog_Table_Log_CreateTime, YCLog_Table_Log_Content], @([[NSDate date] timeIntervalSince1970]), log];
}

#pragma mark - Public Methods

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YCLogManager alloc] init];
    });
    
    return manager;
}

+ (void)log:(NSString *)log {
    [[YCLogManager sharedInstance] insertLog:log];
}

@end
